/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.benkyou.client.network;

import com.benkyou.client.GameClient;
import com.benkyou.common.Player;
import com.benkyou.common.messages.PlayerDisconectMessage;
import com.benkyou.common.messages.PlayerMessage;
import com.benkyou.common.messages.PlayerSyncMessage;
import com.jme3.network.Client;
import com.jme3.network.Message;
import com.jme3.network.MessageListener;
import java.util.ArrayList;

/**
 *
 * @author student
 */
public class PlayerMessageListener implements MessageListener<Client>{
    GameClient gameClient;
    private  ArrayList<Player> players ;
    
    public PlayerMessageListener(GameClient gameClient){
        this.gameClient = gameClient;
         players = new ArrayList<Player>();
    }

    public void messageReceived(Client source, Message m) {
        
        if(m instanceof PlayerMessage){
            PlayerMessage playerMessage = (PlayerMessage) m;
            if(gameClient.isUp() && playerMessage.isMove()){

                Player player;
                player = gameClient.getPlayerByName(playerMessage.getName());
                if(player != null){
                player.setWalkDirection(playerMessage.getX(), playerMessage.getY(), playerMessage.getZ());
                player.setCurrentPosition(playerMessage.getPosX(), playerMessage.getPosY(), playerMessage.getPosZ());
                player.getAvatarControlSystem().setUpdateNeeded(true);
                }
            }else if(!playerMessage.isMove()){
            gameClient.setMainPlayer(playerMessage.getName(), playerMessage.getId(), playerMessage.getUUID());
            gameClient.getFormHandler().startGame();
        
            }
        }
        if(m instanceof PlayerSyncMessage){
            PlayerSyncMessage sync = (PlayerSyncMessage) m;
            for(PlayerMessage play: sync.getLoggedInPlayers()){
              players.add(new Player(play.getName(), play.getId(), play.getUUID()));
            }
            gameClient.processSyncMessage(players);
            players.clear();
           
        }
        if(m instanceof PlayerDisconectMessage){
            PlayerDisconectMessage playerDisconectMessage = (PlayerDisconectMessage) m;
            System.out.println(playerDisconectMessage.getUUID());
            gameClient.removePlayer(playerDisconectMessage.getUUID());
        }
    }
     
}
